# -*- coding:utf8 -*-
import os
import Image
import csv
import cv2
import collections
import cv2.cv as cv
import numpy as np

def generate_CMYK():
    img_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/train224'
    img_flag = 0
    for img in os.listdir(img_folder):
        img_flag += 1
        if img_flag%10000 == 0:
            print 'img_flag: ' + str(img_flag) + '\r',
        path = img_folder + '/' + img
        im = Image.open(path)
        if im.mode == "CMYK":
            im.save('/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/trainCMYK/' + img)

def CMYL_to_RGB():
    img_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/trainCMYK'
    for img in os.listdir(img_folder):
        path = img_folder + '/' + img
        im = Image.open(path)
        im = im.convert('RGB')
        im.save('/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/trainCMYKtoRGB/' + img)

def sampleRGB():
    img_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/test224'
    img_flag = 0
    for img in os.listdir(img_folder):
        img_flag += 1
        path = img_folder + '/' + img
        im = Image.open(path)
        if img_flag%1000 == 0:
            im.save('/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/testSample/' + img)

def to15():
    file = '/home/dell/wxm/Code/JD/log_records/submit/baseline/64/ans_newD_heNor.csv'
    file_ = '/home/dell/wxm/Code/JD/log_records/submit/baseline/64/ans_15.csv'
    f = open(file)
    f_ = open(file_,'wb')
    csvwriter = csv.writer(f_)
    lines = f.readlines()
    for line in lines:
        name, label = line.split(',')
        label = 15
        new_line = [name, str(label)]
        csvwriter.writerow(new_line)


def fanse():
    image = cv.LoadImage('/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/white_train/Train127807.jpg',1)
    size = (image.width,image.height)
    iTmp = cv.CreateImage(size,image.depth,image.nChannels)
    for i in range(image.height):
      for j in range(image.width):
        iTmp[i,j] = (255-image[i,j][0],255-image[i,j][1],255-image[i,j][2])
    cv.NamedWindow('image')
    cv.NamedWindow('iTmp')
    cv.ShowImage('image',image)
    cv.ShowImage('iTmp',iTmp)
    cv.WaitKey(0)

def wash_dataset_by_edge():#去除训练集中CMYK，白色图片
    img_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/train'
    CMYK_flag = 0
    washed_flag = 0
    zero_flag = 0

    for img in os.listdir(img_folder):
        path = img_folder + '/' + img
        im = Image.open(path)
        if im.mode == "CMYK":
            CMYK_flag += 1
            im.save('/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/CMYK_train/' + img)
        if zero_ratio(path):
            zero_flag += 1
            im.save('/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/white_train/' + img)
        else:
            washed_flag += 1
            im.save('/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/washed_train/' + img)
        print "CMYK_flag: " + str(CMYK_flag) + '  |  ',
        print "zero_flag: " + str(zero_flag) + '  |  ',
        print "washed_flag: " + str(washed_flag) + '\r',
def zero_ratio(path):
    im_vec = 256*256
    img = cv2.imread(path)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    detected_edges = cv2.GaussianBlur(gray,(3,3),0)
    dst= cv2.Canny(detected_edges,30,150)
    dst = list(dst.reshape((im_vec,)))
    count_zero = dst.count(0).__float__()
    zero_Ratio = count_zero/im_vec
    if zero_Ratio >= 0.96:
        return True
    elif zero_Ratio < 0.96:
        return False


def wash_dataset_by_RGB():
    img_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/washedUFS_test'
    washed_flag = 0
    RGB_flag = 0
    for img in os.listdir(img_folder):
        path = img_folder + '/' + img
        im = Image.open(path)
        if RGB_ratio_real(path):
            RGB_flag += 1
            im.save('/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/washedUFSW_test/' + img)
        else:
            washed_flag += 1
            im.save('/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/washedUFSUnW_test/' + img)
        print "RGB_flag: " + str(RGB_flag) + '  |  ',
        print "washed_flag: " + str(washed_flag) + '\r',
def RGB_ratio_real(path):#判断是否为白色
    im = cv2.imread(path)
    white_flag = 0
    for i in range(256):
        if list(im[i,i,:]) == [255, 255, 255]:
            white_flag += 1
    if white_flag >= 165:
        return True
    else:
        return False

def wash_fs():
    img_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/test'
    res_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/washedUFS_test'
    UFS_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/UFS_test'
    img_flag = 0
    noise_flag = 0

    for img in os.listdir(img_folder):
        img_flag += 1
        path = img_folder + '/' + img
        path_save = res_folder + '/' + img
        path_UFS = UFS_folder + '/' + img
        im = Image.open(path)
        im_arr = np.asarray(im)
        if im_arr.shape != (256,256,3):
            im.save(path_UFS)
            noise_flag += 1
            print str(im.mode) + ' :  ' + str(im_arr.shape)
        else:
            im.save(path_save)

        print 'img_flag: ' + str(img_flag) + ' | ',
        print "noise_flag: " + str(noise_flag) + '\r' ,

def to_washedWhite():
    img_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/Tem_test'
    res_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/washedUFSUnW_test'
    for img in os.listdir(img_folder):
        path = img_folder + '/' + img
        path_save = res_folder + '/' + img
        im = Image.open(path)
        im.save(path_save)

def generate_new_trainLabel_txt():
    img_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/washedWhite_train'
    src_file = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/train_label.txt'
    res_file = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/washed_train_label.csv'

    deleted_flag = 0
    img_flag = 0

    file_ = file(res_file,'wb')
    csvwriter = csv.writer(file_)

    f = open(src_file)
    lines = f.readlines()
    for line in lines:
        line = line.strip('\n')
        img_flag += 1
        name, label = line.split(',')
        path = img_folder + '/' + name
        try:
            im = Image.open(path)
            new_line = [name, str(label)]
            csvwriter.writerow(new_line)
        except IOError:
            deleted_flag += 1
        print 'img_flag: ' + str(img_flag) + ' | ',
        print 'deleted_flag: ' + str(deleted_flag) + '\r',

def check_number_of_remained_train():
    img_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/washedWhite_train'
    img_flag = 0
    for img in os.listdir(img_folder):
        img_flag += 1
        print "img_flag: " + str(img_flag) + "\r" ,


def wrap_UFS_test():
    img_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/Proc64/test_UFS'
    save_folder = '/media/dell/cb552bf1-c649-4cca-8aca-3c24afca817b/dell/wxm/Data/JD/Proc64/test_UFS_fixed'
    for img in os.listdir(img_folder):
        path = img_folder + '/' + img
        path_save = save_folder + '/' + img
        im = Image.open(path)

        if im.mode == "CMYK":
            im = im.convert('RGB')

        wrap_size = min(im.size)
        max_size = max(im.size)
        crop_point = (max_size - wrap_size)/2
        if max_size == im.size[0]:
            box = (crop_point, 0, crop_point+wrap_size, 0+wrap_size)
        else:
            box = (0, crop_point, 0+wrap_size, crop_point+wrap_size )

        im = im.crop(box)
        im.save(path_save)


if __name__ == "__main__":
    wrap_UFS_test()